﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DoVuiKinhThanh.Helpers
{
    using System.Drawing;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media.Animation;

    public static class ControlHelper
    {
        public static void StartCountdown(Window window, FrameworkElement target, int number, EventHandler completedHandler)
        {
            var colorAnimation = new ColorAnimationUsingKeyFrames();
            var countdownAnimation = new StringAnimationUsingKeyFrames();
            var blackColor = System.Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B);
            var redColor = System.Windows.Media.Color.FromRgb(Color.Red.R, Color.Red.G, Color.Red.B);
            var orangeRedColor = System.Windows.Media.Color.FromRgb(Color.OrangeRed.R, Color.OrangeRed.G, Color.OrangeRed.B);
            for (var i = number; i > 0; i--)
            {
                var keyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(number - i));

                var textFrame = new DiscreteStringKeyFrame(i.ToString(), keyTime);
                countdownAnimation.KeyFrames.Add(textFrame);

                var textColor = blackColor;
                var percent = (i / (number * 1.0)) * 100;
                if (percent <= 20)
                {
                    textColor = redColor;
                }
                else if (percent <= 50)
                {
                    textColor = orangeRedColor;
                }
                var colorFrame = new DiscreteColorKeyFrame(textColor, keyTime);
                colorAnimation.KeyFrames.Add(colorFrame);
            }
            countdownAnimation.KeyFrames.Add(new DiscreteStringKeyFrame("HẾT GIỜ!", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(number + 1))));
            Storyboard.SetTargetName(countdownAnimation, target.Name);
            Storyboard.SetTargetProperty(countdownAnimation, new PropertyPath("Content"));

            colorAnimation.KeyFrames.Add(new DiscreteColorKeyFrame(redColor, KeyTime.FromTimeSpan(TimeSpan.FromSeconds(number + 1))));
            Storyboard.SetTargetName(colorAnimation, target.Name);
            Storyboard.SetTargetProperty(colorAnimation, new PropertyPath("(TextBlock.Foreground).(SolidColorBrush.Color)"));            

            var storyboard = new Storyboard();
            storyboard.Children.Add(countdownAnimation);
            storyboard.Children.Add(colorAnimation);
            storyboard.Completed += completedHandler;
            storyboard.Begin(window);
        }

    }
}
